package utils

import (
	"regexp"
	"strconv"
	"time"

	"github.com/go-errors/errors"
)

var TM = regexp.MustCompile("(\\d{4})(?:[-/])(\\d{1,2})(?:[-/])(\\d{1,2})(\\s(\\d{1,2}):(\\d{1,2})(:(\\d{1,2}))?(?:\\.?)(\\d{3})?)?")

func ParseTime(str string) (*time.Time, error) {

	p := TM.FindAllStringSubmatch(str, 1)

	if len(p) > 0 {

		year, _ := strconv.Atoi(p[0][1])
		month, _ := strconv.Atoi(p[0][2])
		day, _ := strconv.Atoi(p[0][3])
		hour, _ := strconv.Atoi(p[0][5])
		minute, _ := strconv.Atoi(p[0][6])
		second, _ := strconv.Atoi(p[0][8])
		milli, _ := strconv.Atoi(p[0][9])

		tm := time.Date(year, time.Month(month), day, hour, minute, second, milli*1000000, time.Local)
		return &tm, nil
	}

	return nil, errors.New("时间格式不正确!")
}

func GetTimeStr(t int64) string {

	return time.Unix(t, 0).Format("2006-01-02")

}

func GetTime(toBeCharge string) int64 {

	timeLayout := "2006-01-02 15:04:05"                             //转化所需模板
	loc, _ := time.LoadLocation("Local")                            //重要：获取时区
	theTime, _ := time.ParseInLocation(timeLayout, toBeCharge, loc) //使用模板在对应时区转化为time.time类型
	return theTime.Unix()                                           //转化为时间戳 类型是int64
}
